package com.czl.module_storehouse.adapter;

import android.annotation.SuppressLint;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.czl.base.data.bean.tengyun.LocatListBean;
import com.czl.base.data.bean.tengyun.ProductBean;
import com.czl.base.util.SpHelper;
import com.czl.module_service.system.Constants;
import com.czl.module_storehouse.R;
import com.czl.module_storehouse.adapter.tree.ListTree;
import com.czl.module_storehouse.adapter.tree.ListTreeAdapter;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author xubin
 */
public class RemandScanAdapter extends ListTreeAdapter<RemandScanAdapter.BaseViewHolder> {

    private final int mStorehouseLocationId = SpHelper.INSTANCE.decodeInt(Constants.SpKey.STOREHOUSE_LOCATION_ID);
    private final Set<Integer> mIntSet;
    private ListTree.TreeNode mDefaultSelectGroupNode;
    private static final String PAY_LOAD_GROUP = "group";
    private static final String PAY_LOAD_REPLACE = "replace";
    private static final String PAY_LOAD_CHANGE = "change";

    public RemandScanAdapter(ListTree tree, Set<Integer> mIntSet) {
        super(tree);
        this.mIntSet = mIntSet;
    }

    private ListTree.TreeNode selectGroupNode;

    private OnItemViewClickListener mOnItemClickListener;
    private OnProductChangeListener mOnProductChangeListener;
    private int productCount;

    public ListTree.TreeNode getSelectGroupNode() {
        return selectGroupNode;
    }

    public void setOnItemClickListener(OnItemViewClickListener onItemClickListener) {
        mOnItemClickListener = onItemClickListener;
    }

    public void setOnProductChangeListener(OnProductChangeListener onProductChangeListener) {
        mOnProductChangeListener = onProductChangeListener;
    }

    @NonNull
    @Override
    protected RemandScanAdapter.BaseViewHolder onCreateNodeView(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        //创建不同的行View
        if (viewType == R.layout.item_remand_scan_parent) {
            View view = inflater.inflate(viewType, parent, true);
            return new RemandScanAdapter.GroupViewHolder(view);
        } else if (viewType == R.layout.item_remand_scan_children) {
            View view = inflater.inflate(viewType, parent, true);
            return new RemandScanAdapter.ContactViewHolder(view);
        } else {
            return null;
        }
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void onBindNodeViewHolder(RemandScanAdapter.BaseViewHolder viewHolder, int position) {
        //get node at the position
        ListTree.TreeNode node = tree.getNodeByPlaneIndex(position);
        if (node.getLayoutResId() == R.layout.item_remand_scan_parent) {
            if (position == 0 && selectGroupNode == null) {
                selectGroupNode = node;
            }
            //group node
            LocatListBean locatListBean = (LocatListBean) node.getData();
            if (locatListBean.getStorehouseLocatId() == mStorehouseLocationId) {
                mDefaultSelectGroupNode = node;
            }
            RemandScanAdapter.GroupViewHolder gvh = (RemandScanAdapter.GroupViewHolder) viewHolder;
            gvh.tvLoc2.setText(locatListBean.getStorehouseLocatName());
            gvh.tvLoc3.setText(locatListBean.getStorehouseLocatName());

            gvh.tvSelect.setEnabled(locatListBean.isSelected());
            gvh.tvLoc2.setVisibility(locatListBean.isSelected() ? View.VISIBLE : View.GONE);
            gvh.tvLoc3.setVisibility(locatListBean.isSelected() ? View.GONE : View.VISIBLE);
            int childrenCount = node.getChildrenCount();
            locatListBean.setStockNum(childrenCount);
            gvh.tvDelete.setVisibility((childrenCount > 0 || position == 0) ? View.GONE : View.VISIBLE);
            gvh.tvNum.setText("已扫物品：" + childrenCount);
            gvh.tvLoc2.setOnClickListener(v -> {
                //点击选中
                gvh.tvSelect.setEnabled(true);
                locatListBean.setSelected(true);
                set(node);
                if (selectGroupNode != null) {
                    set(node, selectGroupNode);
                }
                selectGroupNode = node;
            });
            gvh.tvLoc3.setOnClickListener(v -> {
                //点击选中
                gvh.tvSelect.setEnabled(true);
                locatListBean.setSelected(true);
                set(node);
                if (selectGroupNode != null) {
                    set(node, selectGroupNode);
                }
                selectGroupNode = node;
            });
            gvh.tvLoc.setOnClickListener(v -> {
                //选择位置
                if (mOnItemClickListener != null) {
                    mOnItemClickListener.onItemClick(node, position);
                }
            });
            //删除位置
            gvh.tvDelete.setOnClickListener(v -> remove(node));
        } else if (node.getLayoutResId() == R.layout.item_remand_scan_children) {
            //child node
            ProductBean productBean = (ProductBean) node.getData();
            RemandScanAdapter.ContactViewHolder cvh = (RemandScanAdapter.ContactViewHolder) viewHolder;
            cvh.tvTitle.setText(productBean.getSortName());
            cvh.tvCode.setText("编号：" + productBean.getProductCode());
            cvh.tvModel.setText("型号：" + productBean.getProductModel());
            cvh.tvRecord.setText(getRecordCodeString(productBean));
            cvh.tvRecordUser.setText(getRecordUserString(productBean));
            cvh.ivDelete.setOnClickListener(v -> remove(node));
        }
    }

    public String getRecordCodeString(ProductBean productBean) {
        if (productBean.getApplyType() == null) {
            return "";
        }
        if (1 == productBean.getApplyType()) {
            return "借用单：" + (productBean.getRecordCode() == null ? "" : productBean.getRecordCode());
        } else {
            return "领用单：" + (productBean.getRecordCode() == null ? "" : productBean.getRecordCode());
        }
    }

    public String getRecordUserString(ProductBean productBean) {
        if (productBean.getApplyType() == null) {
            return "";
        }
        if (1 == productBean.getApplyType()) {
            return "借用人：" + (productBean.getUserName() == null ? "" : productBean.getUserName());
        } else {
            return "领用人：" + (productBean.getUserName() == null ? "" : productBean.getUserName());
        }
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void onBindNodeViewHolder(BaseViewHolder viewHolder, int position, @NonNull List<Object> payloads) {
        super.onBindNodeViewHolder(viewHolder, position, payloads);
        for (Object object : payloads) {
            if (object.equals(PAY_LOAD_GROUP)) {
                if (viewHolder instanceof GroupViewHolder) {
                    ListTree.TreeNode node = tree.getNodeByPlaneIndex(position);
                    int childrenCount = node.getChildrenCount();
                    ((GroupViewHolder) viewHolder).tvNum.setText("已扫物品：" + childrenCount);
                    ((GroupViewHolder) viewHolder).tvDelete.setVisibility((childrenCount > 0 || position == 0) ? View.GONE : View.VISIBLE);
                }
                break;
            } else if (object.equals(PAY_LOAD_REPLACE)) {
                if (viewHolder instanceof GroupViewHolder) {
                    ListTree.TreeNode node = tree.getNodeByPlaneIndex(position);
                    LocatListBean locatListBean = (LocatListBean) node.getData();
                    ((GroupViewHolder) viewHolder).tvLoc2.setText(locatListBean.getStorehouseLocatName());
                    ((GroupViewHolder) viewHolder).tvLoc3.setText(locatListBean.getStorehouseLocatName());
                }
            } else if (PAY_LOAD_CHANGE.equals(object)) {
                if (viewHolder instanceof GroupViewHolder) {
                    ListTree.TreeNode node = tree.getNodeByPlaneIndex(position);
                    LocatListBean locatListBean = (LocatListBean) node.getData();
                    locatListBean.setSelected(true);
                    ((GroupViewHolder) viewHolder).tvSelect.setEnabled(locatListBean.isSelected());
                    ((GroupViewHolder) viewHolder).tvLoc2.setVisibility(locatListBean.isSelected() ? View.VISIBLE : View.GONE);
                    ((GroupViewHolder) viewHolder).tvLoc3.setVisibility(locatListBean.isSelected() ? View.GONE : View.VISIBLE);
                }
            }
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    public void addAll(List<LocatListBean> list, HashSet<Integer> selectProductIds) {
        List<LocatListBean> newList = new ArrayList<>(list);
        for (LocatListBean bean : newList) {
            //创建组们，是root node，所有parent为null
            ListTree.TreeNode groupNode = tree.addNode(null, bean, R.layout.item_remand_scan_parent);
            groupNode.setExpand(true);
            List<ProductBean> productList = bean.getProductList();
            if (productList == null) {
                continue;
            }
            productCount += productList.size();

            for (ProductBean productBean : productList) {
                selectProductIds.add(productBean.getProductId());
                ListTree.TreeNode treeNode = tree.addNode(groupNode, productBean, R.layout.item_remand_scan_children);
                treeNode.setExpand(true);
            }
        }
        notifyDataSetChanged();
    }

    @SuppressLint("NotifyDataSetChanged")
    public void clear() {
        tree.clear();
        notifyDataSetChanged();
    }

    public void add(LocatListBean bean) {
        ListTree.TreeNode groupNode = tree.addNode(null, bean, R.layout.item_remand_scan_parent);
        notifyTreeItemInserted(groupNode, null);
    }

    public void add(ProductBean bean, ListTree.TreeNode groupNode) {
        productCount++;
        if (mOnProductChangeListener != null) {
            mOnProductChangeListener.add(bean, productCount);
        }
        ListTree.TreeNode treeNode = tree.addNode(groupNode, bean, R.layout.item_remand_scan_children);
        if (groupNode != null) {
            Object data = groupNode.getData();
            if (data != null) {
                if (data instanceof LocatListBean) {
                    LocatListBean locatListBean = (LocatListBean) data;
                    List<ProductBean> productList = locatListBean.getProductList();
                    if (productList == null) {
                        productList = new ArrayList<>();
                    }
                    productList.add(bean);
                    locatListBean.setProductList(productList);
                }
            }
        }
        notifyTreeItemInserted(groupNode, treeNode);
        int index = tree.getNodePlaneIndex(groupNode);
        notifyItemChanged(index, PAY_LOAD_GROUP);
    }

    public void remove(ListTree.TreeNode child) {
        productCount--;
        notifyTreeItemRemoved(child);

        ListTree.TreeNode parent = child.getParent();
        if (parent != null) {
            Object data = parent.getData();
            if (data instanceof LocatListBean) {
                List<ProductBean> productList = ((LocatListBean) data).getProductList();
                Object childData = child.getData();
                if (childData != null) {
                    if (childData instanceof ProductBean) {
                        ProductBean bean = (ProductBean) childData;
                        productList.remove(bean);
                        if (mOnProductChangeListener != null) {
                            mOnProductChangeListener.remove(bean, productCount);
                        }
                    }
                }
            }
        } else {
            if (child.getData() instanceof LocatListBean) {
                //删除的节点数据是否是已经选中的,删除选中的节点后选中默认节点
                if (((LocatListBean) child.getData()).isSelected()) {
                    int nodePlaneIndex = tree.getNodePlaneIndex(mDefaultSelectGroupNode);
                    selectGroupNode = mDefaultSelectGroupNode;
                    notifyItemChanged(nodePlaneIndex, PAY_LOAD_CHANGE);
                }
                int storehouseLocatId = ((LocatListBean) child.getData()).getStorehouseLocatId();
                mIntSet.remove(storehouseLocatId);
            }
        }
        if (parent != null) {
            int index = tree.getNodePlaneIndex(parent);
            notifyItemChanged(index, PAY_LOAD_GROUP);
        }
    }

    public void set(ListTree.TreeNode currentNode) {
        if (currentNode != null) {
            int index = tree.getNodePlaneIndex(currentNode);
            notifyItemChanged(index);
        }
    }

    public void set(ListTree.TreeNode currentNode, LocatListBean newBean) {
        if (currentNode != null) {
            currentNode.setData(newBean);
            int index = tree.getNodePlaneIndex(currentNode);
            notifyItemChanged(index, PAY_LOAD_REPLACE);
        }
    }

    public void set(ListTree.TreeNode currentNode, ListTree.TreeNode selectGroupNode) {
        if (selectGroupNode != null && currentNode != null) {
            LocatListBean locatListBean = (LocatListBean) selectGroupNode.getData();
            LocatListBean currentBean = (LocatListBean) currentNode.getData();
            if (locatListBean.getStorehouseLocatId().equals(currentBean.getStorehouseLocatId())) {
                return;
            }
            locatListBean.setSelected(false);
            int index = tree.getNodePlaneIndex(selectGroupNode);
            notifyItemChanged(index);
        }
    }

    public List<LocatListBean> getlocatList() {
        List<LocatListBean> newList = new ArrayList<>();
        List<ListTree.TreeNode> nodes = tree.getNodes();
        List<ProductBean> productBeanList = null;
        for (ListTree.TreeNode treeNode : nodes) {
            Object data = treeNode.getData();
            if (data instanceof LocatListBean) {
                productBeanList = new ArrayList<>();
                LocatListBean bean = (LocatListBean) data;
                bean.setProductList(productBeanList);
                newList.add(bean);
            } else if (data instanceof ProductBean) {
                ProductBean bean = (ProductBean) data;
                if (productBeanList != null) {
                    productBeanList.add(bean);
                }
            }
        }
        return newList;
    }

    public List<ProductBean> getlocatProductList() {
        List<ProductBean> newList = new ArrayList<>();
        List<ListTree.TreeNode> nodes = tree.getNodes();
        for (ListTree.TreeNode treeNode : nodes) {
            Object data = treeNode.getData();
            if (data instanceof ProductBean) {
                ProductBean bean = (ProductBean) data;
                newList.add(bean);
            }
        }
        return newList;
    }

    protected class BaseViewHolder extends ListTreeAdapter<?>.ListTreeViewHolder {
        public BaseViewHolder(View itemView) {
            super(itemView);
        }
    }

    class GroupViewHolder extends RemandScanAdapter.BaseViewHolder {
        TextView tvLoc;
        TextView tvNum;
        TextView tvSelect;
        TextView tvLoc2;
        TextView tvLoc3;
        TextView tvDelete;

        public GroupViewHolder(View itemView) {
            super(itemView);
            tvLoc = itemView.findViewById(R.id.tv_loc);
            tvLoc2 = itemView.findViewById(R.id.text_loc2);
            tvLoc3 = itemView.findViewById(R.id.text_loc3);
            tvNum = itemView.findViewById(R.id.tv_num);
            tvSelect = itemView.findViewById(R.id.tv_select);
            tvDelete = itemView.findViewById(R.id.tv_delete);
        }
    }

    class ContactViewHolder extends RemandScanAdapter.BaseViewHolder {
        TextView tvTitle;
        TextView tvCode;
        TextView tvModel;
        ImageView ivDelete;
        TextView tvRecord;
        TextView tvRecordUser;

        public ContactViewHolder(View itemView) {
            super(itemView);
            tvTitle = itemView.findViewById(R.id.tv_title);
            tvCode = itemView.findViewById(R.id.tv_code);
            tvModel = itemView.findViewById(R.id.tv_model);
            ivDelete = itemView.findViewById(R.id.iv_delete);
            tvRecord = itemView.findViewById(R.id.tv_record);
            tvRecordUser = itemView.findViewById(R.id.tv_record_user);
        }
    }

    public interface OnItemViewClickListener {
        void onItemClick(ListTree.TreeNode treeNode, int position);
    }

    public interface OnProductChangeListener {
        void add(ProductBean bean, int count);

        void remove(ProductBean bean, int count);
    }
}
